<template>
    <el-header class="header">
        <HeaderDemo />
    </el-header>
    <div class="agreement-container">
        <h1>短视频剧本授权协议</h1>
        <div class="agreement-content">
            <p>
                甲方姓名（授权方）：
                <span class="editable" contenteditable="true">{{ writer.real_name }}</span>
            </p>
            <p>
                甲方账号（授权方）：
                <span class="editable" contenteditable="true">{{ writer.account }}</span>
            </p>
            <p>
                乙方（被授权方）：
                <span class="editable" contenteditable="true">{{ user.real_name }}</span>
            </p>
            <p>
                乙方账号（授权方）：
                <span class="editable" contenteditable="true">{{ user.account }}</span>
            </p>
            <p>
                鉴于甲方为短视频剧本《<span class="editable" contenteditable="true">{{ work.wname }}</span>》（以下简称“剧本”）的唯一合法著作权人，
                根据《中华人民共和国著作权法》及相关法律法规的规定，甲乙双方经友好协商，就甲方授权乙方使用该剧本达成如下协议：
            </p>

            <h2>第一条 剧本基本信息</h2>
            <p>
                1.1 剧本名称：
                <span class="editable" contenteditable="true">{{ work.wname }}</span>
            </p>
            <p>
                1.2 剧本作者：
                <span class="editable" contenteditable="true">{{ writer.uname }}</span>
            </p>
            <p>
                1.3 剧本类型：
                <span class="editable" contenteditable="true">{{ work.themename }}</span>（例如：短视频剧本、微电影剧本、广告剧本等）
            </p>
            <p>
                1.4 剧本题材：
                <span class="editable" contenteditable="true">
                    {{ scriptTypes.map(scriptType => scriptType.bname).join('、') }}
                </span>（例如：喜剧、剧情、悬疑等）
            </p>

            <h2>第二条 授权内容</h2>
            <p>
                2.1 甲方特此授予乙方非独家、不可转让的改编权和拍摄权，即乙方有权在本协议约定的范围内，将剧本改编为短视频并进行拍摄制作。
            </p>
            <p>2.2 乙方仅限于以下方式使用剧本：</p>
            <p>
                （1）将剧本改编为时长不超过<span class="editable" contenteditable="true" @input="updateTime">{{ work.time
                    }}</span>分钟的短视频；
            </p>
            <p>
                （2）在<span class="editable" contenteditable="true" @input="updateplatform">{{ work.platform
                    }}</span>（指定平台，如：抖音、快手等）发布改编后的短视频；
            </p>
            <p>
                （3）在中国大陆范围内传播改编后的短视频。
            </p>

            <h2>第三条 授权期限</h2>
            <p>
                本协议自双方签字盖章之日起生效，授权期限为<span class="editable" contenteditable="true" @input="updateage_limit">{{
                    work.age_limit }}</span>年。授权期限届满后，乙方应立即停止使用剧本，并删除或销毁所有基于本协议制作的改编作品。
            </p>

            <h2>第四条 费用与支付方式</h2>
            <p>
                4.1 乙方应向甲方支付一次性授权费用人民币
                <span class="editable" contenteditable="true" @input="convertToChinese">{{ work.authorization_fee
                    }}</span>
                元（大写：<span>{{ chineseAmount }}</span>元整），作为获得本协议项下改编权和拍摄权的对价。
            </p>
            <p>
                4.2 乙方应在本协议签署后<span class="editable" contenteditable="true"></span>日内，以<span class="editable"
                    contenteditable="true"></span>（银行转账、支付宝、微信等）方式全额支付上述费用至甲方指定账户。
            </p>

            <h2>第五条 权利与义务</h2>
            <p>5.1 甲方保证其为剧本的合法著作权人，有权进行本协议项下的授权，且剧本内容不侵犯任何第三方的合法权益。</p>
            <p>5.2 乙方应确保改编后的短视频内容不违反法律法规，不含有侵犯他人知识产权、名誉权、隐私权等合法权益的内容。</p>
            <p>5.3 乙方在使用剧本及改编作品过程中，应尊重甲方的署名权，按照甲方要求的方式在短视频及相关宣传材料中明确标注甲方为原剧本作者。</p>

            <h2>第六条 违约责任</h2>
            <p>任何一方违反本协议约定，应承担违约责任，赔偿守约方因此遭受的直接经济损失。</p>

            <h2>第七条 争议解决</h2>
            <p>因本协议引起的或与本协议有关的任何争议，双方应首先通过友好协商解决；协商不成的，任何一方均有权将争议提交甲方所在地有管辖权的人民法院诉讼解决。</p>

            <h2>第八条 其他条款</h2>
            <p>8.1 本协议未尽事宜，双方可另行签订补充协议，补充协议与本协议具有同等法律效力。</p>
            <p>8.2 本协议一式两份，甲乙双方各执一份，自双方签字或盖章之日起生效。</p>

            <div class="sign-section">
                <div class="sign-block">
                    <p>
                        甲方（签字）：
                        <span v-if="signatures.partyA" class="signature-image">
                            <img :src="signatures.partyA" alt="甲方签字" />
                        </span>
                        <span v-else class="editable"></span>
                    </p>
                    <p>
                        日期：
                        <span class="date-display">{{ datePartyA }}</span>
                    </p>
                </div>
                <div class="sign-block">
                    <p>
                        乙方（签字）：
                        <span v-if="signatures.partyB" class="signature-image">
                            <img :src="signatures.partyB" alt="乙方签字" />
                        </span>
                        <span v-else class="editable"></span>
                    </p>
                    <p>
                        日期：
                        <span class="date-display">{{ datePartyB }}</span>
                    </p>
                </div>
            </div>
        </div>

        <!-- 签名弹出框 -->
        <!-- <div v-if="showSignaturePad" class="signature-pad-modal">
            <canvas ref="signaturePad" class="signature-canvas"></canvas>
            <button @click="saveSignature">保存签名</button>
            <button @click="clearSignature">清除签名</button>
            <button @click="closeSignaturePad">关闭</button>
        </div> -->

        <!-- <div class="action-buttons">
            <button @click="submitAgreement">保存设置</button>
        </div> -->

    </div>
    <!-- 新增的盒子和按钮 -->
    <div class="talk-box">
        <button class="talk-button" @click="conversation">进行洽谈</button>
    </div>


    <!-- 私信框 -->
    <el-drawer v-model="drawer2" :direction="direction" size="auto">
        <!-- <template #header>
            <h4>会话框</h4>
        </template> -->
        <div class="container"
            v-if="sessionList_already != null || sessionList_already.length != 0 || sessionList_already != ''">
            <div class="list">
                <!-- <div v-if="duihua" class="list-item1">

                    <img :src="touxiangUrl" alt="" style="height: 50px;width: 50px;">
                    123456
                </div> -->
                <!-- <div class="label_title" >
                    <p>会话列表</p>
                </div> -->
                <div style="height: auto;overflow: auto;" width="100%">
                    <div :class="curSessionId == item.conversation_id ? 'box_select' : 'box'"
                        v-for="item in sessionList_already" :key="item.conversation_id"
                        style="background-color: bisque;">
                        <!-- <img :src="'http://localhost:8080/api/images/' +item.avatar" alt="" style="height: 50px;width: 50px;"></img> -->
                        <el-tooltip class="box-item" effect="dark" :content="item.list_name" placement="left">
                            <img :src="'http://localhost:8080/api/images/' + item.headImg" alt=""
                                style="height: 50px;width: 50px;" @click="startSession(item)">
                        </el-tooltip>
                        <!-- <div class="box_left" @click="startSession(item)">
                            {{ item.list_name }}
                        </div> -->
                        <div class="right_left">
                            <!-- <div class="right_left_count">
                                {{ item.un_read_count }}
                            </div> -->
                            <!-- <p @click="delSession(item.id)" class="right_left_del">X</p> -->
                            <!-- <div class="right_left_del">
                                <i class="el-icon-close" @click="delSession(item.id)"></i>
                            </div> -->
                        </div>
                    </div>
                </div>

            </div>
            <div class="chat">
                <!-- 聊天对象 -->
                <div style="width: 100%;background-color: antiquewhite;text-align: center;height: 3%;"><span>{{
                    toUname
                        }}</span>
                </div>
                <!-- 聊天框 -->
                <div class="input">
                    <div class="up" ref="messageContainer" id="msg_end">
                        <!-- 加载效果 -->
                        <div v-if="isLoading" class="loading">加载中...</div>
                        <!-- 显示消息 -->
                        <div v-for="(item, i) in list" :key="i">
                            <!-- <div :class="item.senderId === curUserId ? 'msg_right_down' : 'msg_left_down'">
                                {{ item.mdata }}
                            </div>
                            <div>
                                <img src="../img/Logo.png" alt="" style="width: 25px;">
                            </div> -->
                            <!-- 本人发送的消息 -->
                            <div v-if="item.senderId === curUserId" class="msg_right msg">
                                <div class="msg_right_down">
                                    <span v-if="isLink(item.mdata)">
                                        <router-link class="no-underline" :to="getLink(item.mdata)">{{ getLinkText(item.mdata)
                                            }}</router-link>
                                    </span>
                                    <span v-else>{{ item.mdata }}</span>
                                </div>
                                <div class="img_right">
                                    <img :src="fromImgURL" alt="" style="width: 30px;">
                                </div>
                            </div>
                            <!-- 对方发送的消息 -->
                            <div v-else class="msg_left msg">
                                <div class="img_left">
                                    <img :src="'http://localhost:8080/api/images/' + item.avatar" alt=""
                                        style="width: 30px;">
                                </div>
                                <div class="msg_left_down">
                                    <span v-if="isLink(item.mdata)">
                                        <router-link class="no-underline" :to="getLink(item.mdata)">{{ getLinkText(item.mdata)
                                            }}</router-link>
                                    </span>
                                    <span v-else>{{ item.mdata }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 消息发送区 -->
                <div style="width: 100%;height: 4%;">
                    <img src="../../public/images/hetong.png" style="width: 30px;height: 30px;margin-bottom: 2px"
                        @click="GotoAgreementdeal">


                </div>
                <div class="send" style="height: 3%;">

                    <el-input v-model="message" placeholder="请输入内容" class="input-with-select"
                        @keyup.enter.native="sendMsg" :rows="9">
                        <template #append>
                            <el-button type="primary" @click="sendMsg">发送</el-button>
                        </template>
                    </el-input>
                </div>
            </div>

        </div>
        <el-empty :image-size="200" v-if="sessionList_already.length == 0" />

        <!-- <template #default>
        <div>
          <el-radio v-model="radio1" value="Option 1" size="large">
            Option 1
          </el-radio>
          <el-radio v-model="radio1" value="Option 2" size="large">
            Option 2
          </el-radio>
        </div>
      </template> -->
        <!-- <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">cancel</el-button>
          <el-button type="primary" @click="confirmClick">confirm</el-button>
        </div>
      </template> -->
    </el-drawer>
</template>

<script lang="ts" setup>
import { ref, nextTick, onMounted, inject, onBeforeUnmount, onUpdated } from 'vue';
import SignaturePad from 'signature_pad';
import { useRouter, useRoute } from 'vue-router';
import CryptoJS from 'crypto-js';
import HeaderDemo from '../components/HeaderDemo.vue';
import { ElMessageBox } from 'element-plus'
import type { DrawerProps } from 'element-plus';
import { ElMessage } from 'element-plus';
import { Async } from 'jodit/types/modules';
import { isPdfFile } from 'pdfjs-dist';
const axios = inject('axios'); // 注入 axios

// 获取路由信息
const route = useRoute();
// 获取 router 实例
const router = useRouter();

const isLoading = ref(false); // 添加加载状态

// 解密token
function getToken() {
    const encryptedToken = localStorage.getItem('token');
    if (encryptedToken) {
        const secretKey = 'your_secret_key'; // 使用相同的密钥
        const bytes = CryptoJS.AES.decrypt(encryptedToken, secretKey);
        const decryptedToken = bytes.toString(CryptoJS.enc.Utf8);
        return decryptedToken;
    }
    return null;
}

const drawer2 = ref(false)
const direction = ref<DrawerProps['direction']>('rtl')
const radio1 = ref('Option 1')
// const handleClose = (done: () => void) => {
//     ElMessageBox.confirm('Are you sure you want to close this?')
//         .then(() => {
//             done()
//         })
//         .catch(() => {
//             // catch error
//         })
// }
// function cancelClick() {
//     drawer2.value = false
// }
// function confirmClick() {
//     ElMessageBox.confirm(`Are you confirm to chose ${radio1.value} ?`)
//         .then(() => {
//             drawer2.value = false
//         })
//         .catch(() => {
//             // catch error
//         })
// }


// State Variables
const chineseAmount = ref<string>('_________'); // 初始大写内容
const showSignaturePad = ref<boolean>(false); // 控制签名框显示
const currentSignatureParty = ref<'partyA' | 'partyB' | null>(null); // 当前签名的用户（甲方或乙方）
const signatures = ref<{ partyA: string | null; partyB: string | null }>({ partyA: null, partyB: null }); // 存储签名图片
const signaturePad = ref<SignaturePad | null>(null); // 存储 SignaturePad 实例
const canvasRef = ref<HTMLCanvasElement | null>(null); // canvas 表单元素

// 剧本
const work = ref({
    // wname: '', // 剧本名称
    // typeID: '', // 类型
    // copyright: '', // 版权登记号
    // record: '', // 备案号
    // time: '', // 授权时长
    // platform: '', // 授权平台
    // age_limit: '', // 授权年限
    // authorization_fee: '', // 授权费用
});

// 编剧
const writer = ref({
    user_id: '',
    account: '',
    uname: '',
    real_name: '',
    avatar: '',
});

//用户信息，版权购买方
const user = ref({
    uid: '',
    account: '',
    uname: '',
    real_name: '',
});

//头像路径
const toImgURL = ref('');   //对方头像
const fromImgURL = ref(''); //自己头像

// 数据获取相关逻辑
const fetchBookInfo = async (id: string) => {
    console.log("合同=》获取到的剧本id：" + id);
    try {
        const response = await axios.get(`http://localhost:8080/api/getwork/${id}`);
        work.value = response.data; // 假设后端返回的对象结构与work一致
        console.log("获取剧本信息成功=======：", work.value);
        convertToChinese2(work.value.authorization_fee)
    } catch (error) {
        console.error('Error fetching book info:', error);
    }
};

// //获取剧本题材列表
const scriptTypes = ref([]);  // 用于存储从后端获取的题材
const fetchScriptTypes = async (wid) => {
    try {
        const response = await axios.get(`http://localhost:8080/api/getworklabelByWid/${wid}`);
        scriptTypes.value = response.data.data; // 更新题材数据
        console.log('获取题材列表成功：', JSON.stringify(scriptTypes.value, null, 2));
        // console.log('获取题材列表成功：', JSON.stringify(scriptTypes[0].value.bname, null, 2));
    } catch (error) {
        console.error('Error fetching script types:', error);
    }
};


//获取剧本类
// const work_type = ref('');
// const fetchWorkType = async (id) => {

//     try {
//         const response = await axios.get(`http://localhost:8080/api/getworktypeByThemeId/${id}`);
//         work_type.value = response.data; // 更新题材数据
//         console.log('获取剧本类型成功：', JSON.stringify(work_type.value, null, 2));
//         // console.log('获取题材列表成功：', JSON.stringify(work_type[0].value.bname, null))
//     } catch (error) {
//         console.error('遇到错误', error);
//     }
// }


// 获取版权购买方信息(当前用户)
const fetchWriterInfo = async () => {
    console.log("获取用户信息");
    const token = getToken();
    try {
        const response = await axios.get('http://localhost:8080/user/getuser', {
            headers: {
                Authorization: 'Bearer ' + token,
            }
        });
        user.value = response.data.user;
        user.uid = user.value.uid;
        curUserId.value = user.uid;
        curUserName.value = user.value.uname;
        fromImgURL.value = 'http://localhost:8080/api/images/' + user.value.headlmg;  //头像路径换成大写为HEADLMG
        console.log('获取版权购买方信息成功：', user.value);
        console.log("user.account" + user.account);

    } catch (error) {
        console.error('Error fetching writer info:', error);
    }
};

//获取版权所有者信息（通过剧本uid）
const fetchWriterInfoByUid = async (uid: string) => {
    const Token = getToken();
    console.log("获取版权所有者信息:" + uid);
    try {
        const response = await axios.post(`http://localhost:8080/user/getUserById/${uid}`, null, {
            headers: {
                Authorization: 'Bearer ' + Token,
            }
        });
        console.log('获取编剧信息成功：', response.data.data);
        writer.value = response.data.data; // 更新编剧数据
        console.log('获取编剧信息成功：', writer.value);
        toImgURL.value = 'http://localhost:8080/api/images/' + writer.value.headlmg;

    } catch (error) {
        ElMessage.error("请求失败")
    }
}

//根据用户id获取设置头像路径
// const getFilenameFromUrl = (uid: string) => {

//点击进行洽谈触发条件
const duihua = ref(true);
const conversation = async () => {
    //显示对话框
    drawer2.value = true;
    //进行前置判断条件（用户是否曾经进行过对话）；查询聊天记录表
    //const account = fetchWriterInfo();
    await sessionListAlready();   // 获取已存在的会话列表
    console.log("user.account:" + user.account);
    console.log("编剧头像：" + writer.value.headlmg);


    //当用户点击进行洽谈时，创建会话createSession
    createSession(writer.value.uid, writer.value.uname, writer.value.headlmg);

    await sessionListAlready();   // 获取已存在的会话列表

    // await msgList;

    // 如果会话列表不为空，获取第一条会话的内容
    if (sessionList_already.value.length > 0) {
        console.log("sessionList_already.value11111:" + sessionList_already.value);

        const firstSessionId = sessionList_already.value[0].conversation_id;

        // 开始会话并获取消息
        await startSession(sessionList_already.value[0]);

        // 确保在获取消息后滚动到最新消息
        await msgList(firstSessionId); // 获取该会话的消息
    }



};
const GotoAgreementdeal = async () => {


    //获取用户token
    const Token = getToken();
    //获取剧本id
    // 从 route.query 中解构获取 wid 和 uid
    const { wid, uid } = route.query;
    console.log("剧本id：" + wid);
    console.log("跳转合同签订页");
    const Work = work.value;
    console.log("Wid:" + JSON.stringify(Work, null, 2));

    //插入一条版权交易合同表记录
    const res = await axios.post(`http://localhost:8080/api/newTransaction`, Work, {
        headers: {
            'Authorization': 'Bearer ' + Token,
            'Content-Type': 'application/json',
        },

    })
        .then(response => {
            if (response.data.code === 401) {
                ElMessage.error(response.data.message);
            } else {
                ElMessage.success(response.data.message);
                console.log(response.data.message);
                //跳转合同页
                console.log("跳转合同页");

                // 在聊天框中添加跳转消息
                const msg = {
                    senderId: curUserId.value,
                    senderName: curUserName.value,
                    mdata: `我正在协商${work.value.wname}合同内容。请点击查看协议的详细信息。`, // 可以根据需要自定义消息内容
                    // 你可以考虑换成一个对象来表示消息和链接
                    link: { path: '/agreementdeal', query: { wid: wid, uid: user.uid } } // 链接信息
                };
                // 推送到聊天内容中
                list.value.push(msg);


                // 滚动到最新消息
                scrollToBottom();

                // 发送消息到 WebSocket
                if (websock && websock.readyState === WebSocket.OPEN) {
                    websock.send(JSON.stringify(msg)); // 需将消息转换为 JSON 字符串
                    console.log("消息已通过 WebSocket 发送");
                } else {
                    console.error("WebSocket 连接未打开");
                    ElMessage.error("WebSocket 连接未打开");
                }

                // 跳转到合同页面

                router.push({ path: '/agreementdeal', query: { wid: wid,uid: user.uid } });
            }

        })

}

//创建版权买卖双方合同后跳转这个合同页

// 签名相关逻辑
const openSignaturePad = (party: 'partyA' | 'partyB') => {
    console.log('openSignaturePad');
    currentSignatureParty.value = party;
    showSignaturePad.value = true;
    nextTick(initSignaturePad);
};

const initSignaturePad = () => {
    if (canvasRef.value) {
        const canvas = canvasRef.value;
        canvas.width = canvas.offsetWidth;
        canvas.height = canvas.offsetHeight;
        signaturePad.value = new SignaturePad(canvas);
    }
};

const saveSignature = () => {
    if (signaturePad.value?.isEmpty()) {
        alert("请签名！");
    } else {
        const dataUrl = signaturePad.value?.toDataURL();
        if (dataUrl) {
            signatures.value[currentSignatureParty.value!] = dataUrl;
            uploadSignature(dataUrl, currentSignatureParty.value);
            closeSignaturePad();
        }
    }
};

const uploadSignature = (dataUrl: string, party: 'partyA' | 'partyB' | null) => {
    const signatureData = {
        party,
        signature: dataUrl,
    };
    fetch("http://localhost:3000/upload-signature", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(signatureData),
    })
        .then(response => response.json())
        .then(data => {
            console.log("Signature saved:", data);
        })
        .catch(error => {
            console.error("Error saving signature:", error);
        });
};

const clearSignature = () => {
    signaturePad.value?.clear();
};

const closeSignaturePad = () => {
    showSignaturePad.value = false;
};

const convertToChinese = (event: InputEvent) => {
    const value = (event.target as HTMLElement).innerText.trim();
    console.log("=========" + value);
    work.value.authorization_fee = value;
    // if (value && !isNaN(Number(value))) {
    //   chineseAmount.value = numberToChinese(Number(value));
    //   work.Authorization_fee = value;
    //   console.log("输入的金额："+value)
    // } else {
    //   chineseAmount.value = '_________'; // 当内容为空或无效时显示默认下划线
    // }
    convertToChinese2(value)
};

const convertToChinese2 = (value) => {
    console.log("convertToChinese2");

    // 如果输入值是空则直接赋值为下划线 
    //  console.log("value.trim():"+value.trim());

    //  if (value.trim() === '') {
    //   chineseAmount.value = '_________'; // 当内容为空时显示下划线
    //   work.value.authorization_fee = ''; // 清空费用
    //   console.log("work.value.authorization_fee:"+work.value.authorization_fee);

    //   return; // 退出函数
    // }
    // 执行有效性检查，确保是可转换的数字（包括支持负数和小数）
    const numericValue = Number(value);
    console.log("numericValue:" + numericValue);
    if (!isNaN(numericValue) && isFinite(numericValue)) {
        console.log("isFinite(numericValue):" + isFinite(numericValue));
        console.log("numericValue:" + numericValue);
        console.log("value:" + value);
        chineseAmount.value = numberToChinese(numericValue);
        console.log("chineseAmount.value:" + chineseAmount.value);

        work.authorization_fee = value;
        console.log("输入的金额：" + value)
    } else {
        chineseAmount.value = '_________'; // 当内容为空或无效时显示默认下划线
        work.authorization_fee = ''; // 清空费用
    }
}

// 数字转大写的函数
function numberToChinese(n: string): string {
    // 校验输入是否为数字
    if (!/^\d*(\.\d*)?$/.test(n)) return "输入的不是数字";

    const units = ["", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"];
    const chars = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];

    let num = String(n);
    let resultWithUnit = "";
    let decimalPart = "";

    // 处理小数部分
    if (num.indexOf(".") !== -1) {
        const decimals = num.split(".")[1];
        decimalPart = "点";
        for (let i = 0; i < decimals.length; i++) {
            decimalPart += chars[Number(decimals[i])];
        }
        num = num.split(".")[0]; // 去掉小数部分
    }

    let unitPosition = 0; // 用于跟踪当前位对应的单位
    let zeroFlag = false; // 用于跟踪零的连续出现
    let hasNonZero = false; // 标记是否出现过非零数字

    // 处理整数部分
    for (let i = num.length - 1; i >= 0; i--) {
        const currentNum = num[i];
        const unitIndex = unitPosition % 12; // 使用12个单位

        if (currentNum === "0") {
            zeroFlag = true;
        } else {
            if (zeroFlag && hasNonZero) {
                resultWithUnit = chars[0] + resultWithUnit;
                zeroFlag = false; // 连续零结束
            }
            resultWithUnit = chars[Number(currentNum)] + units[unitIndex] + resultWithUnit;
            hasNonZero = true; // 标记为已出现非零数字
        }

        // 添加单位 "万" 或 "亿"
        if (unitIndex === 4 && i > 0) {
            resultWithUnit = "万" + resultWithUnit;
        }
        if (unitIndex === 8 && i > 0) {
            resultWithUnit = "亿" + resultWithUnit;
        }

        unitPosition++;
    }

    // 特殊处理：“壹拾”应改为“拾”
    if (resultWithUnit.startsWith("壹拾")) {
        resultWithUnit = resultWithUnit.replace("壹拾", "拾");
    }

    // 去掉“亿万”的情况，比如输入1000000000
    resultWithUnit = resultWithUnit.replace(/亿万/g, "亿");

    // 去掉末尾的“零”
    resultWithUnit = resultWithUnit.replace(/零+$/, "");

    return resultWithUnit + decimalPart;
}

// 提交修改
const submitAgreement = async () => {
    console.log('提交修改');
    const uWork = {
        wid: route.params.id,
        time: work.value.time,
        age_limit: work.value.age_limit,
        authorization_fee: work.value.authorization_fee,
        platform: work.value.platform,
    };

    try {
        await axios.post('http://localhost:8080/api/updateworkByContract', uWork);
        console.log("提交成功");
    } catch (error) {
        console.error("提交修改失败：" + error);
    }
};

const initiateTalk = () => {
    alert('进入洽谈页面！'); // 这里可以替换为导航到洽谈页面的逻辑
    // router.push({ name: 'TalkPage' })  // 示例：如何使用vue-router导航到”洽谈“页面
};



/////////////////////////////////////////////////////////////////////////
//会话功能区域
// 声明变量
const dialogVisible = ref(false);
const dialogTitle = ref('');
const loginName = ref('');
const message = ref("");
// const list = ref([]);
const list = ref<{ senderId: string; senderName: string; mdata: string }[]>([]);    // 对话列表
const curUserId = ref("");  // 当前用户ID
const curUserName = ref("");
const curSessionId = ref('');
const sessionList_already = ref([]);    // 已经存在的会话列表
const sessionList_not = ref([]);
const toUname = ref('');
//执行一次初始化
const startnum = ref(0);

// WebSocket实例
let websock: WebSocket | null = null;

//输入框响应数据
// const message = ref('');

//输入框回车事件
const handleEnter = () => {
    // 发送消息
    sendMsg();
};

// 生命周期函数
onMounted(() => {
    // 页面创建相关逻辑

});

// 创建对消息容器的引用
const messageContainer = ref(null);

// 页面销毁时关闭WebSocket连接
onBeforeUnmount(() => {
    websocketclose();
});

// WebSocket相关方法
const initWebSocket = (userId: string, sessionId: string) => {
    console.log("开始连接:" + user.value.uid + " | " + sessionId);

    websock = new WebSocket(`ws://localhost:8080/websocket/${user.value.uid}/${sessionId}`);
    websock.onopen = websocketonopen;
    websock.onerror = websocketonerror;
    websock.onmessage = websocketonmessage;
    websock.onclose = websocketclose;
};

const websocketonopen = () => {
    console.log("WebSocket连接成功");
};

const websocketonerror = (e: Event) => {
    console.log("WebSocket连接发生错误", e);
};
// 接收服务器消息
const websocketonmessage = (e) => {
    console.log("收到服务器内容：" + e.data);

    let data = JSON.parse(e.data);
    if (Array.isArray(data)) {
        // 列表数据
        sessionList_already.value = data;
        console.log("sessionList_already:" + sessionList_already);


    } else {
        // 消息数据
        list.value.push(data);
        console.log("list:" + list);
    }
};

const websocketclose = (e?: CloseEvent) => {
    console.log(e);

    if (curUserId.value != null) {
        console.log("curSessionId.value-----------------：" + curSessionId.value);

        if (curSessionId.value != null || curSessionId.value != '') {
            initWebSocket(curUserId.value, curSessionId.value);
        } else {
            initWebSocket(curUserId.value, 99999999);
        }
    }
    console.log("connection closed===================", e);
};
// 滚动到最新消息
const scrollToBottom = () => {
    if (messageContainer.value) {
        nextTick(() => {
            messageContainer.value.scrollTop = messageContainer.value.scrollHeight; // 设置滚动位置为最新消息高度
        });
    }
};

// 消息发送
const sendMsg = () => {
    if (curSessionId.value === '') {
        return ElMessage.error("请选择左边的对话框开始聊天!");
    }
    console.log("发送内容:" + message.value);

    let data = {
        "senderId": curUserId.value,
        "senderName": curUserName.value,
        "mdata": message.value,
    };
    console.log("data:" + JSON.stringify(data));

    console.log("发送内容：" + message.value);


    list.value.push(data);  // 添加到消息列表
    //websock.send(JSON.stringify({ sessionId: sessionList_already.value.conversation_id, message: "Hello" }))

    websock.send(message.value); // 发送消息
    message.value = '';
    console.log("会话消息id" + curSessionId.value);
    // msgList(curSessionId.value);
    scrollToBottom();
};
// //// 用于自动滚动到最新消息
// onUpdated(() => {
//     console.log("onUpdated");
//     const elmnt = document.getElementById('msg_end');
//     if (elmnt) {
//         elmnt.scrollTop = elmnt.scrollHeight; // 滚动到最新消息
//     }
// });







const openDialog = (openName: string) => {
    dialogTitle.value = openName;
    dialogVisible.value = true;
};

// 获取可建立会话列表
const getSessionListNot = () => {
    axios.get(`http://localhost:8080/Conversation/not?userId=${curUserId.value}`)
        .then(response => {
            if (response.data.code === -1) {
                return ElMessage.error(response.data.errDesc);
            }
            sessionList_not.value = response.data.data;
        })
        .catch(error => {
            console.log(error);
        });
};

// 获取已存在的会话列表
const sessionListAlready = () => {
    console.log("开始获取已存在的会话列表");

    axios.get(`http://localhost:8080/Conversation/already?userId=${curUserId.value}`)
        .then(response => {
            if (response.data.code === -1) {
                return $message.error(response.data.errDesc);
            }
            sessionList_already.value = response.data.data;
            // 指定要排在第一位的用户 ID
            const targetUserId = work.value.uid; // 替换为实际的 userId
            console.log("targetUserId:" + targetUserId);
            
            // 排序逻辑
            sessionList_already.value.sort((a, b) => {
                // 将 targetUserId 的会话排在前面
                if (a.toUserId === targetUserId && b.toUserId !== targetUserId) {
                    return -1; // a 在 b 前面
                } else if (a.toUserId !== targetUserId && b.toUserId === targetUserId) {
                    return 1; // b 在 a 前面
                }
                return 0; // 保持原顺序
            });
            console.log("已存在的会话列表：" + JSON.stringify(response.data.data, null, 4));
            //获取最新消息，需要只进行一次获取
            if (sessionList_already.value.length > 0 && startnum.value == 0) {
                console.log("sessionList_already.value22222222222222222222222");

                const firstSessionId = sessionList_already.value[0].conversation_id;
                startSession(sessionList_already.value[0]);
                msgList(firstSessionId); // 获取该会话的消息
                startnum.value = 1;
            }

        })
        .catch(error => {
            console.log(error);
        });
};

// 创建会话
const createSession = (toUserId: string, toUserName: string, avatar: string) => {
    console.log("curUserId.value：" + sessionList_already.value);

    axios.get(`http://localhost:8080/Conversation/createSession?userId=${curUserId.value}&toUserId=${toUserId}&toUserName=${toUserName}&avatar=${avatar}`)
        .then(response => {
            if (response.data.code === -1) {
                return $message.error(response.data.errDesc);
            }
            getSessionListNot();    // 获取未建立会话列表
            sessionListAlready();   // 获取已存在的会话列表
        })
        .catch(error => {
            console.log(error);
        });
};

// 开始会话
const startSession = (item) => {
    const sessionId = item.conversation_id;
    console.log("开始会话:" + sessionId);
    console.log("item:" + JSON.stringify(item));
    toUname.value = item.list_name;
    if (websock !== null) {
        websock.close();
    }
    curSessionId.value = sessionId;
    initWebSocket(curUserId.value, sessionId);
    msgList(sessionId);
    scrollToBottom();
};


// 删除会话
const delSession = (sessionId: string) => {
    axios.get(`http://localhost:8080/delSession?sessionId=${sessionId}`)
        .then(response => {
            if (response.data.code === -1) {
                return $message.error(response.data.errDesc);
            }
            getSessionListNot();
            sessionListAlready();
        })
        .catch(error => {
            console.log(error);
        });
};


// 获取消息数据
const msgList = (conversation_id: string) => {
    isLoading.value = true; // 开始加载
    try {
        axios.get(`http://localhost:8080/getMessageList?sessionId=${conversation_id}`)
            .then(response => {
                if (response.data.code === -1) {
                    return $message.error(response.data.errDesc);
                }
                list.value = response.data.data;
                console.log("获取消息数据：" + JSON.stringify(list.value, null, 4));


                // 从新获取列表
                sessionListAlready();
                scrollToBottom();
            })
            .catch(error => {
                console.log(error);
            });
    } catch (error) {
        console.log(error);
    } finally {
        isLoading.value = false; // 结束加载
    }
};

// 判断消息是否为链接消息
const isLink = (mdata) => {
    try {
        const messageObj = JSON.parse(mdata);
        return messageObj.link !== undefined; // 如果存在 link 字段，则视为链接消息
    } catch (e) {
        return false; // 解析失败则认为不是链接
    }
};

// 获取链接
const getLink = (mdata) => {
    const messageObj = JSON.parse(mdata);
    return {
        path: messageObj.link.path,
        query: messageObj.link.query
    };
};

// 获取链接文本
const getLinkText = (mdata) => {
    const messageObj = JSON.parse(mdata);
    return messageObj.mdata; // 显示的文本可以根据需要选择
};


// 登录或注册
// const loginOrRegister = () => {
//     const thus = { dialogTitle, loginName, curUserId, curUserName, dialogVisible, sessionList_already, sessionList_not };

//     if (dialogTitle.value === "注册") {
//         axios.get(`http://localhost:8080/register?name=${loginName.value}`)
//             .then(response => {
//                 if (response.data.code === -1) {
//                     return $message.error(response.data.errDesc);
//                 }
//                 $message.success("注册成功");
//                 dialogVisible.value = false;
//             })
//             .catch(error => {
//                 console.log(error);
//             });
//     } else if (dialogTitle.value === '登录') {
//         axios.get(`http://localhost:8080/login?name=${loginName.value}`)
//             .then(response => {
//                 console.log(response.data);
//                 if (response.data.code === -1) {
//                     return $message.error(response.data.errDesc);
//                 }
//                 curUserId.value = response.data.data.id;
//                 curUserName.value = response.data.data.name;
//                 dialogVisible.value = false;
//                 getSessionListNot();
//                 sessionListAlready();
//                 startSession("99999999");
//             })
//             .catch(error => {
//                 console.log(error);
//             });
//     }
// };


// 退出登录
const loginOut = () => {
    axios.get(`http://localhost:8080/loginOut?name=${curUserName.value}`)
        .then(response => {
            if (response.data.code === -1) {
                return $message.error(response.data.errDesc);
            }
            curUserId.value = '';
            curUserName.value = '';
            $message.success("退出登录成功");
        })
        .catch(error => {
            console.log(error);
        });
};


// 页面挂载后获取书籍信息
onMounted(async () => {
    // 获取路径下的 id
    // const wid = route.params.id as string;

    // 从 route.query 中解构获取 wid 和 uid
    const { wid, uid } = route.query;
    console.log('路由参数wid:', wid);
    console.log('路由参数uid:', uid);
    await fetchBookInfo(wid);
    await fetchWriterInfo();
    // await fetchWorkType(wid)
    await fetchScriptTypes(wid);
    await fetchWriterInfoByUid(work.value.uid)
    initUser()
});

</script>

<style scoped>
.header {
    height: 80px;
    background-color: #050504;
    margin-bottom: 10px;
}

/* 主容器样式 */
.agreement-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 30px;
    font-family: 'Arial', sans-serif;
    line-height: 1.6;
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 8px;
    box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
}

/* 标题样式 */
h1 {
    text-align: center;
    font-size: 24px;
    font-weight: bold;
}

/* 段落内容样式 */
p {
    text-align: justify;
    text-indent: 2em;
    /* 首行缩进 */
}

/* 二级标题样式 */
h2 {
    font-size: 18px;
    margin-top: 20px;
    font-weight: bold;
}

/* 可编辑区域样式 */
.editable {
    position: relative;
    outline: none;
    display: inline-block;
    min-width: 120px;
    cursor: not-allowed;
    /* 禁用状态的鼠标样式 */
}

.editable:before {
    content: "";
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    border-bottom: 1px solid black;
}

.date-display {
    cursor: default;
    /* 指针样式 */
}

/* 签名区域样式 */
.sign-section {
    display: flex;
    justify-content: space-between;
    margin-top: 40px;
}

.sign-block {
    text-align: left;
    width: 45%;
    cursor: not-allowed;
    /* 禁用状态的鼠标样式 */
}

.sign-block p {
    margin-bottom: 10px;
}

/* 按钮样式 */
button {
    margin-top: 20px;
    padding: 10px 20px;
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}

/* 签名图片 */
.signature-image img {
    max-height: 50px;
    border-bottom: 1px solid black;
    cursor: default;
    cursor: not-allowed;
    /* 禁用状态的鼠标样式 */
}

/* 签名区域样式 */
.editable {
    cursor: pointer;
}

/* 签名弹出框样式 */
.signature-pad-modal {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: white;
    padding: 20px;
    box-shadow: 0 0 15px rgba(0, 0, 0, 0.5);
    z-index: 1000;
}

.signature-canvas {
    border: 1px solid black;
    width: 100%;
    height: 200px;
    display: block;
}

.disabled-area {
    cursor: not-allowed;
    /* 禁用状态的鼠标样式 */
}

.talk-box {
    position: fixed;
    bottom: 30px;
    /* 距离底部30px */
    right: 30px;
    /* 距离右侧30px */
    background-color: #42b983;
    /* 背景色 */
    border-radius: 5px;
    /* 圆角 */
    padding: 10px;
    /* 内边距 */
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
    /* 添加阴影 */
}

.talk-button {
    padding: 10px 15px;
    /* 按钮内边距 */
    background-color: #fff;
    /* 按钮背景色 */
    border: none;
    /* 去除边框 */
    border-radius: 5px;
    /* 圆角 */
    cursor: pointer;
    /* 鼠标光标 */
    color: #007bff;
}

.talk-button:hover {
    background-color: #f0f0f0;
    /* 悬停状态的背景色 */
}

.menu-item2 {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中 */
    height: 98px;
    /* 使其占满菜单项的高度 */
}

.image-container {
    display: flex;
    justify-content: center;
    /* 水平居中 */
    align-items: center;
    /* 垂直居中 */
    height: 100%;
    /* 使其占满容器的高度 */
}

.drawer-box {
    background-color: #cf7070;
}

.container {
    width: auto;
    display: flex;
    /* 设置为 flexbox */
    justify-content: flex-start;
    /* 控制项目对齐方式 */
    align-items: flex-start;
    /* 垂直对齐方式 */
    height: 100%;
}

.list {
    height: 60%;
    width: 50px;
}

.chat {
    /* height: 600px; */
    height: 100%;
    /* height: 300px; */
    width: auto;
    min-width: 450px;
    background-color: #060c36;
    margin-left: 10px;
}

.input {
    width: auto;
    height: 89%;
    overflow: hidden;
    /* 隐藏默认滚动条 */
    position: relative;
    /* 用于绝对定位子元素 */
}

.list-item1 {
    width: 100%;
    height: 50px;
    background-color: #007bff;
    overflow-y: scroll;
    /* 允许垂直滚动 */
    margin-right: -17px;
    /* 如果需要，根据系统滚动条宽度调整 */
    padding-right: 17px;
    /* 添加右边距，防止内容被遮挡 */
}

.up::-webkit-scrollbar {
    display: none;
    /* Safari 和 Chrome */
}

.up {
    scrollbar-width: none;
    /* Firefox */
}

.msg_left {
    display: flex;
    /* 使用 Flexbox 布局 */
    align-items: center;
    /* 垂直居中对齐 */
    justify-content: flex-start;
    /* 水平靠左对齐 */
    margin-bottom: 10px;
    /* 消息之间的间距 */

    width: 385px;
    /* padding-left: 5px; */
    margin-top: 5px;
    /* border: 1px #1890ff solid; */
}

.msg_right {
    display: flex;
    /* 使用 Flexbox 布局 */
    align-items: center;
    /* 垂直居中对齐 */
    justify-content: flex-end;
    /* 水平靠右对齐 */
    margin-bottom: 10px;
    /* 消息之间的间距 */

    width: 385px;
    /* padding-right: 20px; */
    margin-top: 5px;
    /* border: 1px #1890ff solid; */
    text-align: right;
}

.up {
    overflow-y: auto;
    /* 允许溢出时显示垂直滚动条 */
    /* 你原本设置的背景色 */
    padding: 10px;
    /* 适量内边距建议 */
    /* height: 530px; */
    height: 100%;
}

.msg {
    width: 430px;
    margin-top: 5px;
}


.msg_right_down {
    background-color: #e1ffc7;
    /* 消息框的颜色 */
    padding: 5px;
    border-radius: 5px;
}

.msg_left_down {
    background-color: #fff3cd;
    /* 消息框的颜色 */
    padding: 5px;
    border-radius: 5px;
}

.img_right {
    margin-left: 10px;
    /* 图片与消息之间的间距 */
    width: 30px;
    margin-left: 10px;
    /* 图片与消息之间的间距 */
}

.img_left {
    margin-right: 10px;
    /* 图片与消息之间的间距 */
}


/* 会话列表 */
.box_select {
    width: 100%;
    height: 50px;
    /* padding: 1px 5px 1px 5px; */
    display: flex;
    /* justify-self: flex-end; */
    /* 添加底部边框 */
    border-bottom: 1px solid #123bde;
    margin-bottom: 10px;
}

.box {
    width: 100%;
    height: 50px;
    /* padding: 1px 5px 1px 5px; */
    display: flex;
    /* justify-self: flex-end; */
    border-bottom: 1px solid #123bde;
    margin-bottom: 10px;
}

/* .box:hover {
    background-color: gainsboro;
    cursor: pointer;
} */

/* .box_left {
    background-color: #007bff;
    width: 40px;
} */



/* .right_left {
    width: 50px;
    height: 22px;
    display: flex;
    justify-content: space-between;
} */

/* .right_left_count {
    padding-left: 10px;
    width: 20px;
} */

.right_left_del {
    width: 20px;
    padding-left: 10px;
}

.box-item {
    width: 50px;
    margin-top: 10px;
    margin-bottom: 10px;
}
.no-underline {
    text-decoration: none; /* 去掉下划线 */
    /* color: inherit; 保持文本颜色继承父元素颜色 */
}
</style>